package com.comdo.newup_loan.module.store;

import android.Manifest;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.comdo.newup_loan.R;
import com.comdo.newup_loan.adapter.StoreListAdapter;
import com.comdo.newup_loan.base.BaseActivity;
import com.comdo.newup_loan.comom.Config;
import com.comdo.newup_loan.model.Department;
import com.comdo.newup_loan.util.TitleMenuUtil;
import com.comdo.newup_loan.widget.LetterListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * Created by liyuan on 2017/11/2.
 */

public class StoreListActivity extends BaseActivity<StoreListPersenter> implements StoreListContact.View {
    @BindView(R.id.list_view)
    ListView mlistView;
    @BindView(R.id.letter_list_view)
    LetterListView mLetterListView;
    // @BindView(R.id.btn_store_detail)
    Button mStoreDetailBtn;
    // @BindView(R.id.ll_top)
     LinearLayout mTopLayout;
    // @BindView(R.id.tv_name)
    TextView mNameText;
    // @BindView(R.id.tv_adress)
    TextView mAdressText;
    private TextView overlay;
    private List<String> mLetters = new ArrayList<String>();
    private List<String> letterItems = new ArrayList<String>();
    private List<Department> departments = new ArrayList<Department>();
    private Handler handler;
    private Thread overlayThread;
    private StoreListAdapter myAdapter;
    private int mTouchShop;//最小滑动距离
    protected float mFirstY;//触摸下去的位置
    protected float mCurrentY;//滑动时Y的位置
    protected int direction;//判断是否上滑或者下滑的标志

    protected boolean mShow;//判断是否执行了上滑动画
    private Animator mAnimator;//动画属性
    private LocationManager locationManager;
    private String locationProvider;
    private static final String TAG = "StoreListActivity";
    //最近分公司信息
    private Department department;
    private Location location;
    private View headerView;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_store_list;
    }

    @Override
    protected void init() {
        super.init();
        requestPhotoPermiss();
        initLoaction();
        mPresenter.getList();

    }

    private void requestPhotoPermiss() {
        PermissionGen.with(StoreListActivity.this)
                .addRequestCode(100)
                .permissions(
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .request();

    }

    @Override

    public void onRequestPermissionsResult(int requestCode, String[] permissions,

                                           int[] grantResults) {

        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        new TitleMenuUtil(StoreListActivity.this, "门店情况", true);
        initOverlay();
        initHeadView();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    myAdapter.notifyDataSetChanged();
                }
            }
        };
        overlayThread = new Thread() {
            @Override
            public void run() {
                overlay.setVisibility(View.GONE);
            }
        };
        mStoreDetailBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (department != null) {
                    if (Config.loginInfo == null) {
                        showToast("请先登录！");
                    } else {
                        Intent intent = new Intent(StoreListActivity.this, StoreDetailActivity.class);
                        intent.putExtra("id", department.getId());
                        startActivity(intent);
                    }
                }

            }
        });
    }

    @PermissionSuccess(requestCode = 100)
    public void requestPhotoSuccess() {
        initLoaction();
    }

    @Override
    protected boolean translucentStatusBar() {
        return super.translucentStatusBar();
    }

    @Override
    public StoreListPersenter getmPresenter() {
        return new StoreListPersenter();
    }

    @Override
    public void presenterSetView() {
        if (mPresenter != null)
            mPresenter.setView(this);
    }

    @Override
    public void getFail(String failMessage) {
        showToast(failMessage);
    }

    @Override
    public void getNearest(Department datas) {
        department = datas;
        mNameText.setText(department.getName());
        mAdressText.setText(department.getAddress());
    }

    @Override
    public void getList(final List<Department> datas) {
        departments.clear();
        sortList(datas);
        myAdapter = new StoreListAdapter(StoreListActivity.this, departments);
        mlistView.setAdapter(myAdapter);
        if(headerView!=null)
        mlistView.addHeaderView(headerView);
        mTouchShop = ViewConfiguration.get(this).getScaledTouchSlop();//系统级别的一个属性,判断用户的最小滑动距离的,可查看源码为16
        mlistView.setOnTouchListener(new View.OnTouchListener() {//listview的触摸事件
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mFirstY = event.getY();//按下时获取位置
                        break;

                    case MotionEvent.ACTION_MOVE:
                        mCurrentY = event.getY();//得到滑动的位置
                        if (mCurrentY - mFirstY > mTouchShop) {//滑动的位置减去按下的位置大于最小滑动距离  则表示向下滑动
                            direction = 0;//down
                        } else if (mFirstY - mCurrentY > mTouchShop) {//反之向上滑动
                            direction = 1;//up
                        }

                        if (direction == 1) {//判断如果是向上滑动 则执行向上滑动的动画
                            if (mShow) {//判断动画是否执行了  执行了则改变状态
                                //执行往上滑动的动画
                               // tolbarAnim(1);
                                mShow = !mShow;
                            }
                        } else if (direction == 0) {//判断如果是向下滑动 则执行向下滑动的动画
                            if (!mShow) {//判断动画是否执行了  执行了则改变状态
                                //执行往下滑动的动画
                              //  tolbarAnim(0);
                                mShow = !mShow;
                            }
                        }

                        break;
                    case MotionEvent.ACTION_UP:
                        break;

                }
                return false;
            }
        });
        mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                position--;
                if (departments.get(position).getIsFont() == 1)
                    return;
                if (Config.loginInfo == null) {
                    showToast("请先登录！");
                } else {
                    Intent intent = new Intent(StoreListActivity.this, StoreDetailActivity.class);
                    intent.putExtra("id", departments.get(position).getId());
                    startActivity(intent);
                }

            }
        });
        initLetterListView();

    }

    private void initLetterListView() {
        String[] b = letterItems.toArray(new String[letterItems.size()]);
        LetterListView.b = b;
        mLetterListView = (LetterListView) findViewById(R.id.letter_list_view);

        mLetterListView
                .setOnTouchingLetterChangedListener(new LetterListView.OnTouchingLetterChangedListener() {

                    @Override
                    public void onTouchingLetterChanged(String s) {

                        int position = mLetters.indexOf(s);
                        mlistView.setSelection(position);
                        overlay.setText(s);
                        overlay.setVisibility(View.VISIBLE);
                        handler.removeCallbacks(overlayThread);
                        handler.postDelayed(overlayThread, 1500);

                    }
                });
        mLetterListView.postInvalidate();
    }

    //排序
    private void sortList(List<Department> datas) {
        departments.clear();
        ;
        Collections.sort(datas, new Comparator<Department>() {
            @Override
            public int compare(Department lhs, Department rhs) {
                return lhs.getDeptFirstLetter().compareTo(rhs.getDeptFirstLetter());
            }
        });
        String letter = "0";
        for (Department department : datas) {
            if (!TextUtils.isEmpty(department.getDeptFirstLetter())) {
                String cur = department.getDeptFirstLetter();
                if (!letter.equals(cur)) {
                    letter = cur;
                    Department depart = new Department();
                    depart.setIsFont(1);
                    depart.setName(letter);
                    departments.add(depart);
                    mLetters.add(department.getDeptFirstLetter().toUpperCase());
                    Log.e("letter", letter);
                    letterItems.add(letter.toUpperCase());
                }
                departments.add(department);
                mLetters.add(department.getDeptFirstLetter().toUpperCase());
            }
        }
    }

    //字母提示窗口
    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(this);
        overlay = (TextView) inflater.inflate(R.layout.letter_overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    private void initHeadView() {
        headerView = getLayoutInflater().inflate(R.layout.include_storelist_head, null);
        mStoreDetailBtn=(Button) headerView.findViewById(R.id.btn_store_detail);
        mNameText=(TextView) headerView.findViewById(R.id.tv_name);
        mAdressText=(TextView) headerView.findViewById(R.id.tv_adress);
        mTopLayout=(LinearLayout)headerView.findViewById(R.id.ll_top);
    }

    private void tolbarAnim(final int flag) {
        Log.e("tolbarAnim", "flag" + "==");
        if (mAnimator != null && mAnimator.isRunning()) {//判断动画存在  如果启动了,则先关闭
            mAnimator.cancel();
        }
        if (flag == 0) {
            mAnimator = ObjectAnimator.ofFloat(mTopLayout, "translationY", mTopLayout.getTranslationY(), 0);//从当前位置位移到0位置

        } else {
            mAnimator = ObjectAnimator.ofFloat(mTopLayout, "translationY", mTopLayout.getTranslationY(), -mTopLayout.getHeight());//从当前位置移动到布局负高度的wiz
        }
        mAnimator.start();//执行动画


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getWindowManager().removeViewImmediate(overlay);
    }

    private void initLoaction() {
        locationManager = (LocationManager) getSystemService(getApplicationContext().LOCATION_SERVICE);

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度，如果设置为高精度，依然获取不了location。
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(true);//允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗

        //从可用的位置提供器中，匹配以上标准的最佳提供器
        locationProvider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "onCreate: 没有权限 ");
            return;
        }
        location = locationManager.getLastKnownLocation(locationProvider);
        Log.d(TAG, "onCreate: " + (location == null) + "..");
        if (location != null) {
            mStoreDetailBtn.setEnabled(true);
            mPresenter.getNearest(location.getLatitude() + "", location.getLongitude() + "");
        }
        //监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
    }

    /**
     * LocationListern监听器
     * 参数：地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
     */

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle arg2) {

        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {

        }

        @Override
        public void onLocationChanged(Location location) {


        }
    };
}
